#include <func.h>

//服务端
int main(void)
{
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if(fd == -1)
        error(1, errno, "socket");

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi("8080"));
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    if(bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1)
        error(1, errno, "bind");

    if(listen(fd, 10) == -1)
        error(1, errno, "listen");

    int sock_fd = 0;
    fd_set next_set;
    FD_ZERO(&next_set);
    FD_SET(fd, &next_set);
    while(1)
    {
        fd_set set = next_set;
        if(select(20, &set, NULL, NULL, NULL) == -1)
            error(1, errno, "select");
        if(FD_ISSET(fd, &set))
        {
            sock_fd = accept(fd, NULL, NULL);
            FD_CLR(fd, &next_set);
            FD_SET(sock_fd, &next_set);
        }
        if(FD_ISSET(sock_fd, &set))
        {
            char buf[128];
            char file_name[50];
            int count = recv(sock_fd, file_name, 50, 0);

            int file = open(file_name, O_WRONLY | O_CREAT | O_TRUNC, 0666);
            while(1)
            {
                int count = recv(sock_fd, buf, 128, 0);
                if(count == -1)
                    error(1, errno, "recv");
                else if(count == 0)
                {
                    FD_CLR(sock_fd, &next_set);
                    FD_SET(fd, &next_set);
                    close(file);
                    close(sock_fd);
                    break;
                }
                else
                    if(write(file, buf, count) == -1)
                        error(1, errno, "write");
            }
        }
    }

    close(fd);
    return 0;
}

